package de.sendorian.app.forumArchive;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.google.common.io.Resources;

import de.sendorian.app.forumArchive.domain.Forum;
import de.sendorian.app.forumArchive.repository.ForumRepository;
import de.sendorian.util.matcher.PropertyMatcher;

@Component
public class ReadmeCreator implements Runnable {
    
    private static Logger LOG = Logger.getLogger(ReadmeCreator.class);
    
    /**
     * If this matcher matches, the property was not set (otherwise it would
     * have been replaced with its value.
     */
    private static final PropertyMatcher property = new PropertyMatcher();
    
    private String readme;
    
    private String downloadDir;
    
    private ForumRepository forumRepository;
    

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
        ReadmeCreator readmeGenerator = context.getBean(ReadmeCreator.class);
        readmeGenerator.run();
    }
    
    
    @Override
    public void run() {
        createReadme(forumRepository.findAll());
    }
    
    
    public void createReadme(List<Forum> forums) {
        if (readme != null) {
            URL readmeUrl = Resources.getResource(readme);
            for (Forum forum : forums) {
                File forumPath = new File(downloadDir+File.separator+forum.getName()); 
                if (forumPath.exists()) {
                    try {
                        Resources.copy(readmeUrl, new FileOutputStream(new File(forumPath, "readme.txt")));
                    } catch (IOException e) {
                        LOG.error("Could not create readme file", e);
                    }
                }
            }
        }
    }
    
    
    @Value("#{props['readme']}")
    public void setReadme(String readme) {
        this.readme = (property.matches(readme) ? null : readme);
    }
    
    
    @Value("#{config.downloadDir}")
    public void setDownloadDir(String downloadDir) {
        this.downloadDir = downloadDir;
    }
    
    
    @Autowired
    public void setForumRepository(ForumRepository forumRepository) {
        this.forumRepository = forumRepository;
    }
}
